

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="https://image.lxandzjy.top/2022/06/06/8871b9e332dbe.png">
  <link rel="icon" href="https://image.lxandzjy.top/2022/06/06/8871b9e332dbe.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="zjy">
  <meta name="keywords" content="学习笔记,vue,axios,,JavaScript,前端,后端">
  
    <meta name="description" content="axios学习记录官方地址 https:&#x2F;&#x2F;axios-http.com&#x2F;zh&#x2F;docs&#x2F;intro Axios 是一个基于 promise 网络请求库，作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。 特性 从">
<meta property="og:type" content="article">
<meta property="og:title" content="Axios学习记录">
<meta property="og:url" content="https://zjy365.github.io/2021/09/01/Axios%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/index.html">
<meta property="og:site_name" content="土猪的个人博客">
<meta property="og:description" content="axios学习记录官方地址 https:&#x2F;&#x2F;axios-http.com&#x2F;zh&#x2F;docs&#x2F;intro Axios 是一个基于 promise 网络请求库，作用于node.js 和浏览器中。 它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js http 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。 特性 从">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-09-01T12:46:25.000Z">
<meta property="article:modified_time" content="2021-11-21T06:37:28.952Z">
<meta property="article:author" content="zjy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="axios">
<meta name="twitter:card" content="summary_large_image">
  
  
  
  <title>Axios学习记录 - 土猪的个人博客</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"zjy365.github.io","root":"/","version":"1.9.1","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>

  
<meta name="generator" content="Hexo 5.4.2"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>土猪</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('https://image.lxandzjy.top/2022/06/06/aea923ea1a0e8.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Axios学习记录"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2021-09-01 20:46" pubdate>
          2021年9月1日 晚上
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          9.3k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          78 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">Axios学习记录</h1>
            
            <div class="markdown-body">
              
              <h3 id="axios学习记录"><a href="#axios学习记录" class="headerlink" title="axios学习记录"></a>axios学习记录</h3><p>官方地址 <a target="_blank" rel="noopener" href="https://axios-http.com/zh/docs/intro">https://axios-http.com/zh/docs/intro</a></p>
<p>Axios 是一个基于 <em><a target="_blank" rel="noopener" href="https://javascript.info/promise-basics">promise</a></em> 网络请求库，作用于<a target="_blank" rel="noopener" href="https://nodejs.org/"><code>node.js</code></a> 和浏览器中。 它是 <em><a target="_blank" rel="noopener" href="https://www.lullabot.com/articles/what-is-an-isomorphic-application">isomorphic</a></em> 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js <code>http</code> 模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。</p>
<h2 id="特性"><a href="#特性" class="headerlink" title="特性"></a>特性</h2><ul>
<li>从浏览器创建 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequests</a></li>
<li>从 node.js 创建 <a target="_blank" rel="noopener" href="http://nodejs.org/api/http.html">http</a> 请求</li>
<li>支持 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> API</li>
<li>拦截请求和响应</li>
<li>转换请求和响应数据</li>
<li>取消请求</li>
<li>自动转换JSON数据</li>
<li>客户端支持防御<a target="_blank" rel="noopener" href="http://en.wikipedia.org/wiki/Cross-site_request_forgery">XSRF</a></li>
</ul>
<h1 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h1><p>使用 npm:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">$ npm install axios<br></code></pre></td></tr></table></figure>

<p>使用 bower:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">$ bower install axios<br></code></pre></td></tr></table></figure>

<p>使用 yarn:</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs bash">$ yarn add axios<br></code></pre></td></tr></table></figure>

<p>使用 jsDelivr CDN:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>使用 unpkg CDN:</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;https://unpkg.com/axios/dist/axios.min.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>



<h3 id="执行get请求"><a href="#执行get请求" class="headerlink" title="执行get请求"></a>执行get请求</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 上述请求也可以按以下方式完成（可选）</span><br>axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, &#123;<br>    <span class="hljs-attr">params</span>: &#123;<br>      <span class="hljs-attr">ID</span>: <span class="hljs-number">12345</span><br>    &#125;<br>  &#125;)<br>  .<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response);<br>  &#125;)<br>  .<span class="hljs-title function_">catch</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(error);<br>  &#125;)<br>  .<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) &#123;<br>    <span class="hljs-comment">// 总是会执行</span><br>  &#125;);  <br><br><span class="hljs-comment">// 支持async/await用法</span><br><span class="hljs-keyword">async</span> <span class="hljs-keyword">function</span> <span class="hljs-title function_">getUser</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">try</span> &#123;<br>    <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user?ID=12345&#x27;</span>);<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response);<br>  &#125; <span class="hljs-keyword">catch</span> (error) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">error</span>(error);<br>  &#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<h3 id="发起一个-POST-请求"><a href="#发起一个-POST-请求" class="headerlink" title="发起一个 POST 请求"></a>发起一个 <code>POST</code> 请求</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs js">axios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/user&#x27;</span>, &#123;<br>    <span class="hljs-attr">firstName</span>: <span class="hljs-string">&#x27;Fred&#x27;</span>,<br>    <span class="hljs-attr">lastName</span>: <span class="hljs-string">&#x27;Flintstone&#x27;</span><br>  &#125;)<br>  .<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(response);<br>  &#125;)<br>  .<span class="hljs-title function_">catch</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(error);<br>  &#125;);<br></code></pre></td></tr></table></figure>

<h3 id="发起多个并发请求"><a href="#发起多个并发请求" class="headerlink" title="发起多个并发请求"></a>发起多个并发请求</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">function</span> <span class="hljs-title function_">getUserAccount</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">return</span> axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/12345&#x27;</span>);<br>&#125;<br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">getUserPermissions</span>(<span class="hljs-params"></span>) &#123;<br>  <span class="hljs-keyword">return</span> axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/12345/permissions&#x27;</span>);<br>&#125;<br><br><span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">all</span>([<span class="hljs-title function_">getUserAccount</span>(), <span class="hljs-title function_">getUserPermissions</span>()])<br>  .<span class="hljs-title function_">then</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">results</span>) &#123;<br>    <span class="hljs-keyword">const</span> acct = results[<span class="hljs-number">0</span>];<br>    <span class="hljs-keyword">const</span> perm = results[<span class="hljs-number">1</span>];<br>  &#125;);<br><br><br><br></code></pre></td></tr></table></figure>

<h3 id="也可以通过向-axios-传递相关配置来创建请求"><a href="#也可以通过向-axios-传递相关配置来创建请求" class="headerlink" title="也可以通过向 axios 传递相关配置来创建请求"></a>也可以通过向 <code>axios</code> 传递相关配置来创建请求</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs php"><span class="hljs-comment">// 发起一个post请求</span><br><span class="hljs-title function_ invoke__">axios</span>(&#123;<br>  <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;post&#x27;</span>,<br>  <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/user/12345&#x27;</span>,<br>  <span class="hljs-attr">data</span>: &#123;<br>    <span class="hljs-attr">firstName</span>: <span class="hljs-string">&#x27;Fred&#x27;</span>,<br>    <span class="hljs-attr">lastName</span>: <span class="hljs-string">&#x27;Flintstone&#x27;</span><br>  &#125;<br>&#125;);<br></code></pre></td></tr></table></figure>

<h2 id="请求配置"><a href="#请求配置" class="headerlink" title="请求配置"></a>请求配置</h2><p>参见官网<a target="_blank" rel="noopener" href="https://axios-http.com/zh/docs/req_config">https://axios-http.com/zh/docs/req_config</a></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br></pre></td><td class="code"><pre><code class="hljs js">&#123;<br>  <span class="hljs-comment">// `url` 是用于请求的服务器 URL</span><br>  <span class="hljs-attr">url</span>: <span class="hljs-string">&#x27;/user&#x27;</span>,<br><br>  <span class="hljs-comment">// `method` 是创建请求时使用的方法</span><br>  <span class="hljs-attr">method</span>: <span class="hljs-string">&#x27;get&#x27;</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `baseURL` 将自动加在 `url` 前面，除非 `url` 是一个绝对 URL。</span><br>  <span class="hljs-comment">// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL</span><br>  <span class="hljs-attr">baseURL</span>: <span class="hljs-string">&#x27;https://some-domain.com/api/&#x27;</span>,<br><br>  <span class="hljs-comment">// `transformRequest` 允许在向服务器发送前，修改请求数据</span><br>  <span class="hljs-comment">// 它只能用于 &#x27;PUT&#x27;, &#x27;POST&#x27; 和 &#x27;PATCH&#x27; 这几个请求方法</span><br>  <span class="hljs-comment">// 数组中最后一个函数必须返回一个字符串， 一个Buffer实例，ArrayBuffer，FormData，或 Stream</span><br>  <span class="hljs-comment">// 你可以修改请求头。</span><br>  <span class="hljs-attr">transformRequest</span>: [<span class="hljs-keyword">function</span> (<span class="hljs-params">data, headers</span>) &#123;<br>    <span class="hljs-comment">// 对发送的 data 进行任意转换处理</span><br><br>    <span class="hljs-keyword">return</span> data;<br>  &#125;],<br><br>  <span class="hljs-comment">// `transformResponse` 在传递给 then/catch 前，允许修改响应数据</span><br>  <span class="hljs-attr">transformResponse</span>: [<span class="hljs-keyword">function</span> (<span class="hljs-params">data</span>) &#123;<br>    <span class="hljs-comment">// 对接收的 data 进行任意转换处理</span><br><br>    <span class="hljs-keyword">return</span> data;<br>  &#125;],<br><br>  <span class="hljs-comment">// 自定义请求头</span><br>  <span class="hljs-attr">headers</span>: &#123;<span class="hljs-string">&#x27;X-Requested-With&#x27;</span>: <span class="hljs-string">&#x27;XMLHttpRequest&#x27;</span>&#125;,<br><br>  <span class="hljs-comment">// `params` 是与请求一起发送的 URL 参数</span><br>  <span class="hljs-comment">// 必须是一个简单对象或 URLSearchParams 对象</span><br>  <span class="hljs-attr">params</span>: &#123;<br>    <span class="hljs-attr">ID</span>: <span class="hljs-number">12345</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `paramsSerializer`是可选方法，主要用于序列化`params`</span><br>  <span class="hljs-comment">// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)</span><br>  <span class="hljs-attr">paramsSerializer</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">params</span>) &#123;<br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Qs</span>.<span class="hljs-title function_">stringify</span>(params, &#123;<span class="hljs-attr">arrayFormat</span>: <span class="hljs-string">&#x27;brackets&#x27;</span>&#125;)<br>  &#125;,<br><br>  <span class="hljs-comment">// `data` 是作为请求体被发送的数据</span><br>  <span class="hljs-comment">// 仅适用 &#x27;PUT&#x27;, &#x27;POST&#x27;, &#x27;DELETE 和 &#x27;PATCH&#x27; 请求方法</span><br>  <span class="hljs-comment">// 在没有设置 `transformRequest` 时，则必须是以下类型之一:</span><br>  <span class="hljs-comment">// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams</span><br>  <span class="hljs-comment">// - 浏览器专属: FormData, File, Blob</span><br>  <span class="hljs-comment">// - Node 专属: Stream, Buffer</span><br>  <span class="hljs-attr">data</span>: &#123;<br>    <span class="hljs-attr">firstName</span>: <span class="hljs-string">&#x27;Fred&#x27;</span><br>  &#125;,<br>  <br>  <span class="hljs-comment">// 发送请求体数据的可选语法</span><br>  <span class="hljs-comment">// 请求方式 post</span><br>  <span class="hljs-comment">// 只有 value 会被发送，key 则不会</span><br>  <span class="hljs-attr">data</span>: <span class="hljs-string">&#x27;Country=Brasil&amp;City=Belo Horizonte&#x27;</span>,<br><br>  <span class="hljs-comment">// `timeout` 指定请求超时的毫秒数。</span><br>  <span class="hljs-comment">// 如果请求时间超过 `timeout` 的值，则请求会被中断</span><br>  <span class="hljs-attr">timeout</span>: <span class="hljs-number">1000</span>, <span class="hljs-comment">// 默认值是 `0` (永不超时)</span><br><br>  <span class="hljs-comment">// `withCredentials` 表示跨域请求时是否需要使用凭证</span><br>  <span class="hljs-attr">withCredentials</span>: <span class="hljs-literal">false</span>, <span class="hljs-comment">// default</span><br><br>  <span class="hljs-comment">// `adapter` 允许自定义处理请求，这使测试更加容易。</span><br>  <span class="hljs-comment">// 返回一个 promise 并提供一个有效的响应 （参见 lib/adapters/README.md）。</span><br>  <span class="hljs-attr">adapter</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">config</span>) &#123;<br>    <span class="hljs-comment">/* ... */</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `auth` HTTP Basic Auth</span><br>  <span class="hljs-attr">auth</span>: &#123;<br>    <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;janedoe&#x27;</span>,<br>    <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;s00pers3cret&#x27;</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `responseType` 表示浏览器将要响应的数据类型</span><br>  <span class="hljs-comment">// 选项包括: &#x27;arraybuffer&#x27;, &#x27;document&#x27;, &#x27;json&#x27;, &#x27;text&#x27;, &#x27;stream&#x27;</span><br>  <span class="hljs-comment">// 浏览器专属：&#x27;blob&#x27;</span><br>  <span class="hljs-attr">responseType</span>: <span class="hljs-string">&#x27;json&#x27;</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)</span><br>  <span class="hljs-comment">// 注意：忽略 `responseType` 的值为 &#x27;stream&#x27;，或者是客户端请求</span><br>  <span class="hljs-comment">// Note: Ignored for `responseType` of &#x27;stream&#x27; or client-side requests</span><br>  <span class="hljs-attr">responseEncoding</span>: <span class="hljs-string">&#x27;utf8&#x27;</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `xsrfCookieName` 是 xsrf token 的值，被用作 cookie 的名称</span><br>  <span class="hljs-attr">xsrfCookieName</span>: <span class="hljs-string">&#x27;XSRF-TOKEN&#x27;</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称</span><br>  <span class="hljs-attr">xsrfHeaderName</span>: <span class="hljs-string">&#x27;X-XSRF-TOKEN&#x27;</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `onUploadProgress` 允许为上传处理进度事件</span><br>  <span class="hljs-comment">// 浏览器专属</span><br>  <span class="hljs-attr">onUploadProgress</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">progressEvent</span>) &#123;<br>    <span class="hljs-comment">// 处理原生进度事件</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `onDownloadProgress` 允许为下载处理进度事件</span><br>  <span class="hljs-comment">// 浏览器专属</span><br>  <span class="hljs-attr">onDownloadProgress</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">progressEvent</span>) &#123;<br>    <span class="hljs-comment">// 处理原生进度事件</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数</span><br>  <span class="hljs-attr">maxContentLength</span>: <span class="hljs-number">2000</span>,<br><br>  <span class="hljs-comment">// `maxBodyLength`（仅Node）定义允许的http请求内容的最大字节数</span><br>  <span class="hljs-attr">maxBodyLength</span>: <span class="hljs-number">2000</span>,<br><br>  <span class="hljs-comment">// `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。</span><br>  <span class="hljs-comment">// 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`)，</span><br>  <span class="hljs-comment">// 则promise 将会 resolved，否则是 rejected。</span><br>  <span class="hljs-attr">validateStatus</span>: <span class="hljs-keyword">function</span> (<span class="hljs-params">status</span>) &#123;<br>    <span class="hljs-keyword">return</span> status &gt;= <span class="hljs-number">200</span> &amp;&amp; status &lt; <span class="hljs-number">300</span>; <span class="hljs-comment">// 默认值</span><br>  &#125;,<br><br>  <span class="hljs-comment">// `maxRedirects` 定义了在node.js中要遵循的最大重定向数。</span><br>  <span class="hljs-comment">// 如果设置为0，则不会进行重定向</span><br>  <span class="hljs-attr">maxRedirects</span>: <span class="hljs-number">5</span>, <span class="hljs-comment">// 默认值</span><br><br>  <span class="hljs-comment">// `socketPath` 定义了在node.js中使用的UNIX套接字。</span><br>  <span class="hljs-comment">// e.g. &#x27;/var/run/docker.sock&#x27; 发送请求到 docker 守护进程。</span><br>  <span class="hljs-comment">// 只能指定 `socketPath` 或 `proxy` 。</span><br>  <span class="hljs-comment">// 若都指定，这使用 `socketPath` 。</span><br>  <span class="hljs-attr">socketPath</span>: <span class="hljs-literal">null</span>, <span class="hljs-comment">// default</span><br><br>  <span class="hljs-comment">// `httpAgent` and `httpsAgent` define a custom agent to be used when performing http</span><br>  <span class="hljs-comment">// and https requests, respectively, in node.js. This allows options to be added like</span><br>  <span class="hljs-comment">// `keepAlive` that are not enabled by default.</span><br>  <span class="hljs-attr">httpAgent</span>: <span class="hljs-keyword">new</span> http.<span class="hljs-title class_">Agent</span>(&#123; <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> &#125;),<br>  <span class="hljs-attr">httpsAgent</span>: <span class="hljs-keyword">new</span> https.<span class="hljs-title class_">Agent</span>(&#123; <span class="hljs-attr">keepAlive</span>: <span class="hljs-literal">true</span> &#125;),<br><br>  <span class="hljs-comment">// `proxy` 定义了代理服务器的主机名，端口和协议。</span><br>  <span class="hljs-comment">// 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。</span><br>  <span class="hljs-comment">// 使用 `false` 可以禁用代理功能，同时环境变量也会被忽略。</span><br>  <span class="hljs-comment">// `auth`表示应使用HTTP Basic auth连接到代理，并且提供凭据。</span><br>  <span class="hljs-comment">// 这将设置一个 `Proxy-Authorization` 请求头，它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。</span><br>  <span class="hljs-comment">// 如果代理服务器使用 HTTPS，则必须设置 protocol 为`https`</span><br>  <span class="hljs-attr">proxy</span>: &#123;<br>    <span class="hljs-attr">protocol</span>: <span class="hljs-string">&#x27;https&#x27;</span>,<br>    <span class="hljs-attr">host</span>: <span class="hljs-string">&#x27;127.0.0.1&#x27;</span>,<br>    <span class="hljs-attr">port</span>: <span class="hljs-number">9000</span>,<br>    <span class="hljs-attr">auth</span>: &#123;<br>      <span class="hljs-attr">username</span>: <span class="hljs-string">&#x27;mikeymike&#x27;</span>,<br>      <span class="hljs-attr">password</span>: <span class="hljs-string">&#x27;rapunz3l&#x27;</span><br>    &#125;<br>  &#125;,<br><br>  <span class="hljs-comment">// see https://axios-http.com/zh/docs/cancellation</span><br>  <span class="hljs-attr">cancelToken</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">CancelToken</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">cancel</span>) &#123;<br>  &#125;),<br><br>  <span class="hljs-comment">// `decompress` indicates whether or not the response body should be decompressed </span><br>  <span class="hljs-comment">// automatically. If set to `true` will also remove the &#x27;content-encoding&#x27; header </span><br>  <span class="hljs-comment">// from the responses objects of all decompressed responses</span><br>  <span class="hljs-comment">// - Node only (XHR cannot turn off decompression)</span><br>  <span class="hljs-attr">decompress</span>: <span class="hljs-literal">true</span> <span class="hljs-comment">// 默认值</span><br><br>&#125;<br></code></pre></td></tr></table></figure>
<h2 id="拦截器"><a href="#拦截器" class="headerlink" title="拦截器"></a>拦截器</h2><p>在请求或响应被 then 或 catch 处理前拦截它们。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-comment">// 添加请求拦截器</span><br>axios.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">config</span>) &#123;<br>    <span class="hljs-comment">// 在发送请求之前做些什么</span><br>    <span class="hljs-keyword">return</span> config;<br>  &#125;, <span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-comment">// 对请求错误做些什么</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error);<br>  &#125;);<br><br><span class="hljs-comment">// 添加响应拦截器</span><br>axios.<span class="hljs-property">interceptors</span>.<span class="hljs-property">response</span>.<span class="hljs-title function_">use</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">response</span>) &#123;<br>    <span class="hljs-comment">// 2xx 范围内的状态码都会触发该函数。</span><br>    <span class="hljs-comment">// 对响应数据做点什么</span><br>    <span class="hljs-keyword">return</span> response;<br>  &#125;, <span class="hljs-keyword">function</span> (<span class="hljs-params">error</span>) &#123;<br>    <span class="hljs-comment">// 超出 2xx 范围的状态码都会触发该函数。</span><br>    <span class="hljs-comment">// 对响应错误做点什么</span><br>    <span class="hljs-keyword">return</span> <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error);<br>  &#125;);<br></code></pre></td></tr></table></figure>





<h2 id="取消请求（还没用过。。）"><a href="#取消请求（还没用过。。）" class="headerlink" title="取消请求（还没用过。。）"></a>取消请求（还没用过。。）</h2><p>使用 <em>cancel token</em> 取消一个请求。</p>
<blockquote>
<p>Axios 的 cancel token API 是基于被撤销 <a target="_blank" rel="noopener" href="https://github.com/tc39/proposal-cancelable-promises">cancelable promises proposal</a>。</p>
</blockquote>
<p>可以使用 <code>CancelToken.source</code> 工厂方法创建一个 cancel token ，如下所示：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">CancelToken</span> = axios.<span class="hljs-property">CancelToken</span>;<br><span class="hljs-keyword">const</span> source = <span class="hljs-title class_">CancelToken</span>.<span class="hljs-title function_">source</span>();<br><br>axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/12345&#x27;</span>, &#123;<br>  <span class="hljs-attr">cancelToken</span>: source.<span class="hljs-property">token</span><br>&#125;).<span class="hljs-title function_">catch</span>(<span class="hljs-keyword">function</span> (<span class="hljs-params">thrown</span>) &#123;<br>  <span class="hljs-keyword">if</span> (axios.<span class="hljs-title function_">isCancel</span>(thrown)) &#123;<br>    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(<span class="hljs-string">&#x27;Request canceled&#x27;</span>, thrown.<span class="hljs-property">message</span>);<br>  &#125; <span class="hljs-keyword">else</span> &#123;<br>    <span class="hljs-comment">// 处理错误</span><br>  &#125;<br>&#125;);<br><br>axios.<span class="hljs-title function_">post</span>(<span class="hljs-string">&#x27;/user/12345&#x27;</span>, &#123;<br>  <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;new name&#x27;</span><br>&#125;, &#123;<br>  <span class="hljs-attr">cancelToken</span>: source.<span class="hljs-property">token</span><br>&#125;)<br><br><span class="hljs-comment">// 取消请求（message 参数是可选的）</span><br>source.<span class="hljs-title function_">cancel</span>(<span class="hljs-string">&#x27;Operation canceled by the user.&#x27;</span>);<br></code></pre></td></tr></table></figure>

<p>也可以通过传递一个 executor 函数到 <code>CancelToken</code> 的构造函数来创建一个 cancel token：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><code class="hljs js"><span class="hljs-keyword">const</span> <span class="hljs-title class_">CancelToken</span> = axios.<span class="hljs-property">CancelToken</span>;<br><span class="hljs-keyword">let</span> cancel;<br><br>axios.<span class="hljs-title function_">get</span>(<span class="hljs-string">&#x27;/user/12345&#x27;</span>, &#123;<br>  <span class="hljs-attr">cancelToken</span>: <span class="hljs-keyword">new</span> <span class="hljs-title class_">CancelToken</span>(<span class="hljs-keyword">function</span> <span class="hljs-title function_">executor</span>(<span class="hljs-params">c</span>) &#123;<br>    <span class="hljs-comment">// executor 函数接收一个 cancel 函数作为参数</span><br>    cancel = c;<br>  &#125;)<br>&#125;);<br><br><span class="hljs-comment">// 取消请求</span><br><span class="hljs-title function_">cancel</span>();<br></code></pre></td></tr></table></figure>



<h2 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 封装axios</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><span class="hljs-comment">// import &#123; Message &#125; from &#x27;element-ui&#x27;</span><br><span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/store&#x27;</span><br><span class="hljs-keyword">import</span> &#123; getToken &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@/utils/auth&#x27;</span><br><br><span class="hljs-keyword">const</span> service = axios.<span class="hljs-title function_">create</span>(&#123;<br>  <span class="hljs-comment">// baseURL: process.env.BASE_API, // api的base_url</span><br>  <span class="hljs-attr">timeout</span>: <span class="hljs-number">5000</span> <span class="hljs-comment">// 请求超时时间</span><br>&#125;)<br><br><span class="hljs-comment">// 请求拦截器,通过vuex查询是否有token,有则对每一个请求头部加上 token字段,error则通过Promise返回error</span><br>service.<span class="hljs-property">interceptors</span>.<span class="hljs-property">request</span>.<span class="hljs-title function_">use</span>(<span class="hljs-function"><span class="hljs-params">config</span> =&gt;</span> &#123;<br>  <span class="hljs-keyword">if</span> (store.<span class="hljs-property">getters</span>.<span class="hljs-property">token</span>) &#123;<br>    config.<span class="hljs-property">headers</span>[<span class="hljs-string">&#x27;X-token&#x27;</span>] = <span class="hljs-title function_">getToken</span>()<br>  &#125;<br>  <span class="hljs-keyword">return</span> config<br>&#125;, <span class="hljs-function"><span class="hljs-params">error</span> =&gt;</span> &#123;<br>  <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(error)<br>  <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(error)<br>&#125;)<br><br><span class="hljs-comment">// 响应拦截器,通过 response定义的code来标志请求的状态,you can do something</span><br>service.<span class="hljs-property">interceptors</span>.<span class="hljs-property">response</span>.<span class="hljs-title function_">use</span>(<br>  <span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response,<br>  <span class="hljs-comment">//  const res = response.data;</span><br>  <span class="hljs-comment">//     if (res.code !== 20000) &#123;</span><br>  <span class="hljs-comment">//       Message(&#123;</span><br>  <span class="hljs-comment">//         message: res.message,</span><br>  <span class="hljs-comment">//         type: &#x27;error&#x27;,</span><br>  <span class="hljs-comment">//         duration: 5 * 1000</span><br>  <span class="hljs-comment">//       &#125;);</span><br>  <span class="hljs-comment">//       // 50008:非法的token; 50012:其他客户端登录了;  50014:Token 过期了;</span><br>  <span class="hljs-comment">//       if (res.code === 50008 || res.code === 50012 || res.code === 50014) &#123;</span><br>  <span class="hljs-comment">//         MessageBox.confirm(&#x27;你已被登出，可以取消继续留在该页面，或者重新登录&#x27;, &#x27;确定登出&#x27;, &#123;</span><br>  <span class="hljs-comment">//           confirmButtonText: &#x27;重新登录&#x27;,</span><br>  <span class="hljs-comment">//           cancelButtonText: &#x27;取消&#x27;,</span><br>  <span class="hljs-comment">//           type: &#x27;warning&#x27;</span><br>  <span class="hljs-comment">//         &#125;).then(() =&gt; &#123;</span><br>  <span class="hljs-comment">//           store.dispatch(&#x27;FedLogOut&#x27;).then(() =&gt; &#123;</span><br>  <span class="hljs-comment">//             location.reload();// 为了重新实例化vue-router对象 避免bug</span><br>  <span class="hljs-comment">//           &#125;);</span><br>  <span class="hljs-comment">//         &#125;)</span><br>  <span class="hljs-comment">//       &#125;</span><br>  <span class="hljs-comment">//       return Promise.reject(&#x27;error&#x27;);</span><br>  <span class="hljs-comment">//     &#125; else &#123;</span><br>  <span class="hljs-comment">//       return response.data;</span><br>  <span class="hljs-comment">//     &#125;</span><br><br>  <span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> &#123;<br>    <span class="hljs-title class_">Promise</span>.<span class="hljs-title function_">reject</span>(err)<br>  &#125;<br>)<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> service<br><br></code></pre></td></tr></table></figure>




              
            </div>
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0/" class="category-chain-item">学习笔记</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/JavaScript/">#JavaScript</a>
      
        <a href="/tags/axios/">#axios</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Axios学习记录</div>
      <div>https://zjy365.github.io/2021/09/01/Axios学习记录/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>zjy</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2021年9月1日</div>
        </div>
      
      
      <div class="license-meta-item">
        <div>许可协议</div>
        <div>
          
            
            
              <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
              <span class="hint--top hint--rounded" aria-label="BY - 署名">
                <i class="iconfont icon-by"></i>
              </span>
              </a>
            
          
        </div>
      </div>
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2021/09/05/%E6%95%B0%E7%BB%84%E5%8E%BB%E9%87%8D/" title="数组去重的方法">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">数组去重的方法</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2021/08/21/%E5%B8%B8%E8%A7%81%E7%9A%84%E7%BD%91%E7%AB%99%E6%94%BB%E5%87%BB/" title="常见网站攻击 （未完成）">
                        <span class="hidden-mobile">常见网站攻击 （未完成）</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  






    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
  
    <!-- 备案信息 ICP for China -->
    <div class="beian">
  <span>
    <a href="http://beian.miit.gov.cn/" target="_blank" rel="nofollow noopener">
      豫ICP备2021008845号-1
    </a>
  </span>
  
</div>

  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>






  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      headingSelector : CONFIG.toc.headingSelector || 'h1,h2,h3,h4,h5,h6',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      collapseDepth   : CONFIG.toc.collapseDepth || 0,
      scrollSmooth    : true,
      headingsOffset  : -boardTop
    });
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }
  });
</script>


  <script>
  (function() {
    var enableLang = CONFIG.code_language.enable && CONFIG.code_language.default;
    var enableCopy = CONFIG.copy_btn;
    if (!enableLang && !enableCopy) {
      return;
    }

    function getBgClass(ele) {
      return Fluid.utils.getBackgroundLightness(ele) >= 0 ? 'code-widget-light' : 'code-widget-dark';
    }

    var copyTmpl = '';
    copyTmpl += '<div class="code-widget">';
    copyTmpl += 'LANG';
    copyTmpl += '</div>';
    jQuery('.markdown-body pre').each(function() {
      var $pre = jQuery(this);
      if ($pre.find('code.mermaid').length > 0) {
        return;
      }
      if ($pre.find('span.line').length > 0) {
        return;
      }

      var lang = '';

      if (enableLang) {
        lang = CONFIG.code_language.default;
        if ($pre[0].children.length > 0 && $pre[0].children[0].classList.length >= 2 && $pre.children().hasClass('hljs')) {
          lang = $pre[0].children[0].classList[1];
        } else if ($pre[0].getAttribute('data-language')) {
          lang = $pre[0].getAttribute('data-language');
        } else if ($pre.parent().hasClass('sourceCode') && $pre[0].children.length > 0 && $pre[0].children[0].classList.length >= 2) {
          lang = $pre[0].children[0].classList[1];
          $pre.parent().addClass('code-wrapper');
        } else if ($pre.parent().hasClass('markdown-body') && $pre[0].classList.length === 0) {
          $pre.wrap('<div class="code-wrapper"></div>');
        }
        lang = lang.toUpperCase().replace('NONE', CONFIG.code_language.default);
      }
      $pre.append(copyTmpl.replace('LANG', lang).replace('code-widget">',
        getBgClass($pre[0]) + (enableCopy ? ' code-widget copy-btn" data-clipboard-snippet><i class="iconfont icon-copy"></i>' : ' code-widget">')));

      if (enableCopy) {
        Fluid.utils.createScript('https://lib.baomitu.com/clipboard.js/2.0.10/clipboard.min.js', function() {
          var clipboard = new window.ClipboardJS('.copy-btn', {
            target: function(trigger) {
              var nodes = trigger.parentNode.childNodes;
              for (var i = 0; i < nodes.length; i++) {
                if (nodes[i].tagName === 'CODE') {
                  return nodes[i];
                }
              }
            }
          });
          clipboard.on('success', function(e) {
            e.clearSelection();
            e.trigger.innerHTML = e.trigger.innerHTML.replace('icon-copy', 'icon-success');
            setTimeout(function() {
              e.trigger.innerHTML = e.trigger.innerHTML.replace('icon-success', 'icon-copy');
            }, 2000);
          });
        });
      }
    });
  })();
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
